package com.juxing.webserver.action.front;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.juxing.sdk.concurrent.ThreadPool;
import com.juxing.sdk.util.MobileUtil;
import com.juxing.sdk.util.StringUtil;
import com.juxing.service.accountCenter.IAccountCenterService;
import com.juxing.service.accountCenter.bean.UserAccessTokenBean;
import com.juxing.service.imCenter.IImCenterService;
import com.juxing.service.imCenter.bean.UserRcTokenBean;
import com.juxing.service.smsCenter.ISmsCenterService;
import com.juxing.service.smsCenter.SmsSendType;
import com.juxing.service.userCenter.IUserCenterService;
import com.juxing.service.userCenter.bean.UserBean;
import com.juxing.webserver.action.BaseAction;
import com.juxing.webserver.common.ReturnCodeConstant;

/**
 * 用户注册等账号相关请求
 * @author brochen
 * @mail mongibello@163.com
 * @created 2016年2月4日
 *
 */
@Controller
@RequestMapping("front/account")
public class FrontAccountAction extends BaseAction {
	
	private static final Logger logger = LoggerFactory.getLogger(FrontAccountAction.class);
	
	@Autowired
	private IAccountCenterService accountCenterService;
	@Autowired
	private IImCenterService imCenterService;
	@Autowired
	private IUserCenterService userCenterService;
	@Autowired
	private ISmsCenterService smsCenterService;
	@Autowired
	private ThreadPool threadPool;
	
	/**
	 * 判断昵称是否使用过
	 * @param request
	 * @param response
	 * @param nickname
	 * @return
	 */
	@RequestMapping("isNicknameUsed.json")
	public ModelAndView isNicknameUsed(HttpServletRequest request, HttpServletResponse response
			,@RequestParam String nickname
			,@RequestParam String imgCode
			,@RequestParam String imgCodeKey
			) {
		if(StringUtil.isEmpty(nickname) || StringUtil.isEmpty(imgCodeKey) || StringUtil.isEmpty(imgCode)) {
			return this.initErrorView(ReturnCodeConstant.PARAM_ERROR);
		}
		int chkCode = this.validateImgCode(imgCodeKey, imgCode);
		if(chkCode != 0) {
			return this.initErrorView(ReturnCodeConstant.GRAPH_CHK_CODE_ERROR);
		}
		ModelAndView view = this.initSuccessView("front/account/isNicknameUsed");
		int used = userCenterService.isNicknameUsed(nickname) ? 1 : 0;
		view.addObject("used", used);
		return view;
	}
	
	/**
	 * 获取手机验证码
	 * @param request
	 * @param response
	 * @param mobile
	 * @param imgCode
	 * @param imgCodeKey
	 * @return
	 */
	@RequestMapping("getMobileChkCode.json")
	public ModelAndView getMobileChkCode(HttpServletRequest request, HttpServletResponse response
			,@RequestParam String mobile			//手机号
			,@RequestParam String imgCode			//图片验证码
			,@RequestParam String imgCodeKey		//图片验证码key
			,@RequestParam(required=false) String testEnvSend		//测试环境是否发送
			) {
		if(StringUtil.isEmpty(mobile) || StringUtil.isEmpty(imgCode) || StringUtil.isEmpty(imgCodeKey)) {
			return this.initErrorView(ReturnCodeConstant.PARAM_ERROR);
		}
		if(!MobileUtil.isValidMobile(mobile)) {
			return this.initErrorView(ReturnCodeConstant.PARAM_ERROR, "手机号不正确");
		}
		int chkCode = this.validateImgCode(imgCodeKey, imgCode);
		if(chkCode != 0) {
			return this.initErrorView(ReturnCodeConstant.GRAPH_CHK_CODE_ERROR);
		}
		if(!this.isOnlineEnv() && !"1".equals(testEnvSend)) {//如果不是线上环境 且 测试环境要求发送
			return this.initSuccessView();
		}
		int ret = smsCenterService.sendCode(mobile, SmsSendType.REG);
		if(ret == 0) {//发送正常
			return this.initSuccessView();
		}
		if(ret <0) {
			return this.initErrorView(ReturnCodeConstant.SMS_SEND_FREQUENCY);
		}
		return this.initSuccessView();
	}
	
	/**
	 * 注册
	 * @return
	 */
	@RequestMapping("reg.json")
	public ModelAndView reg(HttpServletRequest request, HttpServletResponse response
			,@RequestParam String mobile		//手机号
			,@RequestParam String password		//密码
			,@RequestParam String mobileChkCode	//手机校验码
			,@RequestParam String nickname) {	//昵称
		
		//数据校验
		if(StringUtil.isEmpty(mobile)
				|| StringUtil.isEmpty(password)
				|| StringUtil.isEmpty(mobileChkCode)
				|| StringUtil.isEmpty(nickname)) {
			return this.initErrorView(ReturnCodeConstant.PARAM_ERROR);
		}
		if(mobile.length() != 11 || !MobileUtil.isValidMobile(mobile)) {
			return this.initErrorView(ReturnCodeConstant.PARAM_ERROR);
		}
		//到sms中心校验手机验证码
		if(this.isOnlineEnv() || !"999999".equals(mobileChkCode)) {//如果是线上环境,或者非线上环境,非6个9校验码
			if(!smsCenterService.checkCode(mobile, SmsSendType.REG, mobileChkCode)) {
				return this.initErrorView(ReturnCodeConstant.MOBILE_CHK_CODE_ERROR);
			}
		}
		//校验账号是否已经存在
		int userId = accountCenterService.queryUserIdByMobile(mobile);
		if(userId > 0) {
			UserBean user = userCenterService.queryByUserId(userId);
			if(user != null) {//账号已存在
				return this.initErrorView(ReturnCodeConstant.ACCOUNT_EXISTED);
			}
		}
		//校验昵称是否已经存在
		if(userCenterService.isNicknameUsed(nickname)) {
			return this.initErrorView(ReturnCodeConstant.ACCOUNT_NICKNAME_EXISTED);
		}
		//注册账户
		UserAccessTokenBean  uatBean = accountCenterService.regByMobile(mobile, password);
		
		//生成用户信息
		final UserBean user = new UserBean();
		user.setUserId(uatBean.getUserId());
		user.setNickname(nickname);
		user.setAge(0);
		user.setHeadUrl("");//TODO
		user.setSex(0);
		
		//账户注册成功，生成用户融云token
		UserRcTokenBean userRcTokenBean = imCenterService.refreshUserRcToken(user.getUserId(), user.getNickname(), user.getHeadUrl());
		if(userRcTokenBean == null) {
			logger.error("can not get user[{}] rcToken.");
			return this.initErrorView(ReturnCodeConstant.SERVER_ERROR);
		}
		
		userCenterService.insert(user);
		
		
		ModelAndView view = this.initSuccessView("front/account/reg");
		view.addObject("uatBean", uatBean);
		return view;
	}
	
	/**
	 * 登录
	 * @param request
	 * @param response
	 * @param mobile
	 * @param password
	 * @return
	 */
	@RequestMapping("login.json")
	public ModelAndView login(HttpServletRequest request, HttpServletResponse response
			,@RequestParam String mobile		//手机号
			,@RequestParam String password) {		//密码
		
		int userId = accountCenterService.queryUserIdByMobile(mobile);
		if(userId <= 0) {
			return this.initErrorView(ReturnCodeConstant.USER_NOT_EXIST);
		}
		if(!accountCenterService.checkUserPassword(userId, password)) {
			return this.initErrorView(ReturnCodeConstant.ACCOUNT_PWD_NOT_MATCHED);
		}
		final UserBean user = userCenterService.queryByUserId(userId);
		if(user == null) {
			return this.initErrorView(ReturnCodeConstant.USER_NOT_EXIST);
		}
		UserAccessTokenBean  uatBean = accountCenterService.updateAccessToken(userId);
		
		//账户登录成功，异步刷新用户融云token
		UserRcTokenBean userRcTokenBean = imCenterService.getUserRcToken(userId);
		if(userRcTokenBean == null) {
			//顺心一遍
			userRcTokenBean = imCenterService.refreshUserRcToken(user.getUserId(), user.getNickname(), user.getHeadUrl());
		}
		if(userRcTokenBean == null) {
			logger.error("can not get user[{}] rcToken.");
			return this.initErrorView(ReturnCodeConstant.SERVER_ERROR);
		}
		
		ModelAndView view = this.initSuccessView("front/account/login");
		view.addObject("uatBean", uatBean);
		return view;
	}
	
}
